const { getPetDetails, isPet, editIntegral, isCollection, petCollection, updateCollectionStatus } = require("../model/petDetailsModel")
module.exports = {
  // 获取宠物详情数据
  getPetDetails: async (ctx) => {
    const { pet_id } = ctx.request.query;
    // 获取宠物详情数据
    let res = await getPetDetails(pet_id)
    // 如果为空数据则没有数据
    if (res.length === 0) {
      ctx.body = {
        status: 404,
        msg: "没有数据"
      }
      return;
    }
    ctx.body = {
      status: 200,
      msg: "获取成功",
      data: res
    }
  },
  // 收藏宠物
  petCollection: async (ctx) => {
    const { user_id, cover_collection_userId, pet_id, collection_status } = ctx.request.body;
    // 查询宠物信息表中是否有该用户且pet_id对应
    let petFlag = await isPet(cover_collection_userId, pet_id)
    if (petFlag.length === 0) {
      return ctx.body = {
        status: 404,
        msg: "未找到数据"
      }
    } else {
      // 根据收藏修改积分
      editIntegral(cover_collection_userId, collection_status);
    }
    // 判断是否在收藏表中
    let flag = await isCollection(user_id, pet_id)
    // 如果是[]就添加收藏 不在收藏表中
    if (flag.length === 0) {
      // 收藏宠物
      let res = await petCollection(user_id, pet_id, collection_status)
      if (res.affectedRows === 1) {
        ctx.body = {
          status: 200,
          msg: "收藏成功"
        }
      }
    } else {
      // 根据用户id和宠物id修改收藏状态
      let res = await updateCollectionStatus(user_id, pet_id, collection_status)
      if (res.affectedRows === 1) {
        if (collection_status == "true") {
          ctx.body = {
            status: 200,
            msg: "收藏成功"
          }
        }
        if (collection_status == "false") {
          ctx.body = {
            status: 200,
            msg: "取消成功"
          }
        }
      }
    }
  },
  // 获取收藏状态
  getCollectStatus: async (ctx) => {
    const { user_id, pet_id } = ctx.request.query;
    // 判断是否在收藏表中
    let res = await isCollection(user_id, pet_id)
    // 没有在收藏表中就直接返回false
    if (res.length === 0) {
      ctx.body = {
        status: 200,
        msg: "获取成功",
        collection_status: "false"
      }
    } else {
      ctx.body = {
        status: 200,
        msg: "获取成功",
        collection_status: res[0].collection_status
      }
    }
  }
}